package lock;

import java.util.concurrent.locks.ReentrantReadWriteLock;

public class ReentrantReadWriteLockDemo {
    private final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
    private int data;

    public void read() {

        lock.readLock().lock();
        try {
            System.out.println("读操作开始");
            // 读操作逻辑
            System.out.println("读操作结束");
        } finally {
            lock.readLock().unlock();
        }
    }

    public void write() {
        lock.writeLock().lock();
        try {
            System.out.println("写操作开始");
            // 写操作逻辑
            Thread.sleep(1000);
            System.out.println("写操作结束");
        } catch (Exception e) {
        } finally {
            lock.writeLock().unlock();
        }
    }

    public static void main(String[] args) {
        ReentrantReadWriteLockDemo demo = new ReentrantReadWriteLockDemo();

        // 创建多个线程同时读操作
        Thread readThread1 = new Thread(() -> demo.read());
        Thread readThread2 = new Thread(() -> demo.read());
        readThread1.start();
        readThread2.start();

        // 创建一个线程写操作
        Thread writeThread = new Thread(() -> demo.write());
        Thread writeThread1 = new Thread(() -> demo.write());
        writeThread.start();
        writeThread1.start();
    }
}